<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog"
  >
    <el-form ref="addFormRef" v-loading="loading" :model="formData" :rules="rules" size="" label-width="160px">
      <el-row justify="start" class="d_left">
        <el-col :span="itemSpan" :offset="0">
          <el-form-item label="是否置顶" prop="content">
            <!-- <editor v-if="formData.id != 0" :data="formData" /> -->
            <el-tooltip content="置顶的通知会出现在APP的首页,仅允许置顶一条通知" placement="right" effect="light">
              <el-switch v-model="formData.isTop" inline-prompt active-text="置顶" inactive-text="不置顶" />
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan" class="">
          <el-form-item label="通知内容" prop="content">
            <!-- <editor v-if="formData.id != 0" :data="formData" /> -->
            <el-input v-model="formData.content" type="textarea" :rows="10" placeholder="请输入通知内容" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan" class="">
          <el-form-item label="相关附件">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="选择指定对象" prop="limitReaderType">
            <el-select v-model="formData.limitReaderType" class="m-2" placeholder="请选择指定对象" size="large">
              <el-option v-for="item in LimitReaderType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">发布</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//编辑器
// import editor from "@/views/common/WangEditor/index.vue";

import { addSysNotify, editSysNotify, getSysNotifyById } from "@/api/notify/index";
import { SysNotifyEditForm } from "@/api/notify/types";
import { getDicts } from "@/store/modules/dict";

import { ElForm, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useScreen } from "@/store/modules/screen";
import { fa } from "element-plus/es/locale";
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(600);
const itemSpan = ref(24);
const LimitReaderType = getDicts("limitReaderType");
const fileList = ref<UploadUserFile[]>([]);

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "",
      id: 0,
    }),
  },
});

const emit = defineEmits(["sendClose"]);
const loading = ref(false);
const addFormRef = ref(ElForm);
const formData = reactive<SysNotifyEditForm>({
  attachmentIds: [],
  isTop: false,
});
const { dialogAddOrEdit } = toRefs(props);

const rules = reactive<FormRules<SysNotifyEditForm>>({
  content: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
  limitReaderType: [{ required: true, message: "请选择指定对象", trigger: "blur" }],
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
  } else {
    screenWidth.value = 600;
  }
}
onMounted(async () => {
  initScreen();
  loadData();
});

const loadData = async () => {
  if (dialogAddOrEdit.value.id == 0) {
    loading.value = true;
    const res = await getSysNotifyById(dialogAddOrEdit.value.id);
    if (res.type === 0) {
      if (res.success) {
        formData.id = res.data.id;
        console.log("新增通知返回数据,res.data:");
        console.log(res.data);
        console.log("formData:");
        console.log(formData);
      } else {
      }
    } else {
    }
    loading.value = false;
    return;
  }
  loading.value = true;
  const res = await getSysNotifyById(dialogAddOrEdit.value.id);
  if (res.type === 0) {
    if (res.success) {
      formData.content = res.data.content;
      formData.limitReaderType = res.data.limitReaderType;
      formData.isTop = res.data.isTop;
      formData.id = res.data.id;
      if (res.data.attachments) {
        let list = Array<any>();
        res.data.attachments.forEach((item: any) => {
          list.push({
            name: item.friendlyName,
            url: item.objectFilePath,
            status: "success",
            uid: item.id,
          });
        });
        fileList.value = list;
      }
    } else {
    }
  } else {
  }
  loading.value = false;
};

//上传相关

const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialogAddOrEdit.value.visible = false;
  emit("sendClose", "add", true);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addFormRef.value.resetFields();
  addFormRef.value.clearValidate();
  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = dialogAddOrEdit.value.id;
      if (fileList.value.length > 0) {
        formData.attachmentIds = fileList.value.map((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              return item.response.data;
            } else {
              return item.uid;
            }
          }
        });
      }
      if (id) {
        //原型图无修改逻辑不做修改处理
        editSysNotify(formData)
          .then((response) => {
            if (response.type === 0) {
              if (response.success) {
                closeDialog();
              } else {
                ElMessage.error(response.msg);
              }
            } else {
              ElMessage.error(response.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        addSysNotify(formData)
          .then((response) => {
            if (response.type === 0) {
              if (response.success) {
                closeDialog();
              } else {
                ElMessage.error(response.msg);
              }
            } else {
              ElMessage.error(response.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style scoped>
:deep().el-upload-list {
  width: 250px;
}
</style>
